package com.bascker.algorithm.practice.str;

import java.util.Objects;

/**
 * 给定一个字符串，验证它是否是回文串，只考虑字母和数字字符，可忽略字母的大小写 。
 * 说明：本题中将空字符串定义为有效的回文串。
 *
 * For example:
 *   in: "A man, a plan, a canal: Panama"     out: true
 *   in: "race a car"                         out: false
 *
 * @apiNote from leetcode T125
 * @implNote https://gitee.com/bascker/algorithm/wikis/4%E3%80%81%E9%AA%8C%E8%AF%81%E5%9B%9E%E6%96%87%E4%B8%B2?sort_id=2976479
 * @author bascker
 */
public class CheckPalindrome {

    public boolean isPalindrome(String s) {
        if (Objects.isNull(s) || s.trim().length() == 0) {
            return true;
        }

        // 双指针法
        int len = s.length();
        int l = 0, r = len - 1;

        while (l < r) {
            char cL = Character.toUpperCase(s.charAt(l));
            char cR = Character.toUpperCase(s.charAt(r));

            if (!isValidChar(cL)) {
                l ++;
                continue;
            }

            if (!isValidChar(cR)) {
                r --;
                continue;
            }

            if (cL !=cR) {
                return false;
            }

            l ++;
            r --;
        }

        return true;
    }

    private boolean isValidChar(char ch) {
        return (ch >= 'a' && ch <= 'z')
                || (ch >= 'A' && ch <= 'Z')
                || (ch >= '0' && ch <= '9');
    }

}
